package fms.core;

import fms.acarsMsgProcessUtil.DownLinkDatagramHeader;
import fms.acarsMsgProcessUtil.RawDatagram;
import fms.dao.CptSendService;
import fms.model.CptSend;
import fms.util.ConfUtil;
import fms.util.ObjectUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by adcc on 2016/6/21.
 */
public class MasFilter implements IFilter{

    private Logger logger = Logger.getLogger(FlpFilter.class);
    // 风温下行请求报文的SMI列表
    private List downQeqList = new ArrayList();

    public MasFilter() {
        File fBaseParam = new File(ConfUtil.props.getProperty("baseParamFilePath"));
        final SAXReader readerBaseParam = new SAXReader();
        try {
            final Document paraseRulenDoc = readerBaseParam.read(fBaseParam);
            Element uniqueObject = (Element) paraseRulenDoc.selectSingleNode("/baseParamter/coreService/flpController/replySMI");
            String[] downQeqSMI = uniqueObject.getText().split(",");
            for (int i = 0; i < downQeqSMI.length; i++) {
                downQeqList.add(downQeqSMI[i]);
            }
        } catch (final DocumentException e) {
            logger.error(e.getMessage());
        }
    }
    @Override
    public boolean isFilter(String aContent) {
//        logger.debug("[MAS报文过滤] 开始进行报文过滤...");
        if (aContent.contains("<?xml") && aContent.contains("<request>")) {
            return false;
        }
        else if (aContent.contains("<?xml") && aContent.contains("FMS")) {
            return false;
        }
        else{
            DownLinkDatagramHeader msgHeader = null;
            String msgText = "";
            try {
                msgHeader = DownLinkDatagramHeader.Parse(RawDatagram.GetHeader(aContent));
                msgText = RawDatagram.GetBody(aContent);
            }
            catch (Exception e) {
                logger.error("报文头解析出错！" + e.getMessage() + "\r\n出错报文为：\r\n" + aContent);
                // 报头解析异常，该报文不是正规的acars报文，可略过
                return false;
            }
            int indexofSMI=0;
            if(msgText.startsWith("/")){
                indexofSMI=msgText.indexOf(".")+1;
            }
            if (!ObjectUtil.isBlank(msgHeader.getSmi()) && (downQeqList.indexOf(msgHeader.getSmi()) >= 0) && msgHeader.getSmi().equals("MAS")) {
                logger.debug("收到MAS确认报！");
                int indexMas=aContent.indexOf("/MA ");
                CptSendService cptSendService = ConfUtil.getSingletonApplicationContextDao().getBean("cptSendService", CptSendService.class);
                if(indexMas==-1){
                    logger.info("MAS报文不符合规范，报文原文：\r\n"+aContent);
                }
                else{
                    String masNum=aContent.substring(indexMas+4,indexMas+7);
                    String originMas=aContent.substring(indexMas+4,indexMas+8);
                    List<CptSend> cptSendlist=cptSendService.findCptSendbymsgId(masNum+"A");
                    if(cptSendlist!=null&&cptSendlist.size()>0){
                        CptSend cptSend=cptSendlist.get(0);
                        cptSend.setAppUpMsgId(originMas);
                        cptSendService.saveOrUpdate(cptSend);
                    }
                }
                logger.info("MAS确认报文已处理！");
                return true;
            }
            //合并REJ报，SMI为FML,IMI为REJ
            else if(msgText.contains("REJ")&&!msgText.contains("REJFPN")&&!msgText.contains("REJPWI")){
                logger.debug("收到REJ拒绝报！");
                int indexRej=msgText.indexOf("SN");
                String msgId=msgText.substring(indexRej+2,indexRej+12).trim();
                CptSendService cptSendService = ConfUtil.getSingletonApplicationContextDao().getBean("cptSendService", CptSendService.class);
                List listsend = cptSendService.findCptSendbymsgId(msgId);
                if(listsend != null && listsend.size() > 0){
                    CptSend cptSend = (CptSend)listsend.get(0);
                    cptSend.setFmcrejection(msgText);
                    cptSendService.saveOrUpdate(cptSend);
                    logger.info("[结束]飞机FMC下发的(风温/飞行计划)拒绝报文处理");
                }
                else{
                    logger.info("无法找到数据库中对应飞行计划ID："+msgId);
                }

                logger.debug("REJ拒绝报处理已完成！");
                return true;
            }
            else {
//                logger.debug("不是MAS确认报或REJ拒绝报！" );
                return  false;
            }
        }
    }
}
